<template>
  <base-dialog
    title="群聊机器人测试"
    ref="baseDialog"
    @handleClose="handleClose"
    @handleSubmit="handleSubmit"
    width="42%"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="145px">
      <el-form-item label="模板内容" prop="content">
        <el-input v-model="form.content" type="textarea" placeholder="请输入模板内容" readonly />
      </el-form-item>
      <el-form-item
        v-for="param in form.params"
        :key="param"
        :label="'参数 {' + param + '}'"
        :prop="'templateParams.' + param"
      >
        <el-input v-model="form.templateParams[param]" :placeholder="'请输入 ' + param + ' 参数'" />
      </el-form-item>
    </el-form>
  </base-dialog>
</template>

<script>
import { send } from "@/api/message/robot/template"

export default {
  name: "testDialog",
  data() {
    return {
      title: "",
      form: {
        content: undefined,
        params: undefined,
        templateCode: undefined,
        templateParams: {}
      },
      rules: {
        templateCode: [{ required: true, message: "模版编码不能为空", trigger: "blur" }],
        templateParams: {}
      }
    }
  },
  methods: {
    init(item) {
      this.$refs.baseDialog.dialogVisible = true
      if (item) {
        this.form.content = item.content
        this.form.params = item.params
        this.form.templateCode = item.code
        this.form.templateParams = item.params.reduce(function (obj, item) {
          obj[item] = undefined
          return obj
        }, {})
        // 根据 item 重置 rules
        this.rules.templateParams = item.params.reduce(function (obj, item) {
          obj[item] = { required: true, message: "参数 " + item + " 不能为空", trigger: "change" }
          return obj
        }, {})
      }
    },
    handleClose() {
      this.form = {
        content: undefined,
        params: undefined,
        mobile: undefined,
        templateCode: undefined,
        templateParams: {}
      }
      this.$refs.baseDialog.dialogVisible = false
    },
    // 提交表单
    handleSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            await send(this.form)
            this.$message({
              type: "success",
              message: "提交发送成功！"
            })
            this.$emit("updatePage")
            this.handleClose()
          } catch (error) {
            this.$message({
              type: "success",
              message: "提交发送失败！"
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-select,
.picker,
.el-input-number {
  width: 100%;
}
</style>
